package com.icinema.server;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.icinema.client.Message;
import com.icinema.client.RatingService;
import com.icinema.vo.Movie;
import com.icinema.vo.Rating;

public class RatingServiceImpl extends RemoteServiceServlet implements
		RatingService {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4073095429578840302L;
	DatastoreService datastore;
	
	public RatingServiceImpl() {
		datastore = DatastoreServiceFactory.getDatastoreService();
	}
	public void delete(String key){
		datastore.delete(KeyFactory.stringToKey(key));
	}
	
	@Override
	public Message deleteRating(String key) {
		Query query = new Query(Movie.class.getSimpleName());
		query.addFilter("ratingId", FilterOperator.EQUAL, key);
		Message msg = new Message();
		 if(datastore.prepare(query).asIterable(FetchOptions.Builder.withDefaults()).iterator().hasNext()){
			 msg.setErr_msg("This Rating is used by movies.");
			 return msg;
		 }
		 delete(key);
		 return msg;		
	}
	@Override
	public List<Rating> getRatings() {
		Query query = new Query(Rating.class.getSimpleName());
		//query.addFilter("photoKey", FilterOperator.EQUAL, image.getKey());
		
		List<Rating> results = new ArrayList<Rating>();
		
		for(Entity entity : datastore.prepare(query).asIterable(FetchOptions.Builder.withDefaults())) {
			Rating rating = new Rating();
			rating.setName((String)entity.getProperty("name"));
			rating.setId(KeyFactory.keyToString(entity.getKey()));
			results.add(rating);
		}
		
		return results;
	}

	@Override
	public String addNewRating(String ratingName) {
			Entity ratingEntity = new Entity(Rating.class.getSimpleName());
			ratingEntity.setProperty("name",ratingName);
			Key key = datastore.put(ratingEntity);
			String encodedKey = KeyFactory.keyToString(key);
			return encodedKey;
	}
}